﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Hematology.Data;
using Hematology.Data.Interface;
using Hematology.Tools;
using Hematology.Tools.Storage;
using Hematology.Tools.Text;
using Hematology.UserSite.Controls;
using NgoResource = Hematology.UserSite.App_GlobalResources.UserSite;

namespace Hematology.UserSite.admin
{
	public partial class Locations : NgoPage
	{
		#region Properties

		protected int CountryId
		{
			get { return Convert.ToInt32(ViewState["CountryId"]); }
			set { ViewState["CountryId"] = value; }
		}

		protected int RegionId
		{
			get { return Convert.ToInt32(ViewState["RegionId"]); }
			set { ViewState["RegionId"] = value; }
		}

		protected string StartLetter
		{
			get { return ViewState["StartLetter"].ToString(); }
			set { ViewState["StartLetter"] = value; }
		}

		protected EnumHelper.GeographicPoint CurrentGeographicPoint
		{
			get
			{
				return ViewState["CurrentGeographicPoint"] != null
						   ? (EnumHelper.GeographicPoint)Enum.Parse(typeof(EnumHelper.GeographicPoint), ViewState["CurrentGeographicPoint"].ToString())
						   : EnumHelper.GeographicPoint.Countries;
			}
			set { ViewState["CurrentGeographicPoint"] = value; }
		}

		#endregion

		private void FillLetterList()
		{
			string[] cLetterList = TextHelper.RussianAlphabet;

			rptAlphabetLinks.DataSource = cLetterList;
			rptAlphabetLinks.DataBind();
		}

		private void FillCountries(string startLetter)
		{
			IEnumerable<IGeoItem> lCountries = new List<IGeoItem>(Country.GetAllCountries(null).Cast<IGeoItem>());
			if (!String.IsNullOrEmpty(startLetter))
			{
				lCountries = lCountries.Where(i => i.Name.StartsWith(startLetter));
			}

			CacheHelper.SetGeoItems(lCountries);

			rptGeoPoint.DataSource = lCountries;
			rptGeoPoint.DataBind();
		}

		private void FillCountriesCombo()
		{
			List<Country> lCountries = new List<Country>
			                           	{
			                           		new Country
			                           			{
			                           				Id = 0,
			                           				Name = NgoResource.resSelectCountryCombo
			                           			}
			                           	};
			lCountries.AddRange(Country.GetAllCountries(true));
			ddlCountry.DataSource = lCountries;
			ddlCountry.DataBind();
		}

		private void FillRegions(int countryId, string startLetter)
		{
			rptGeoPoint.DataSource = null;
			rptGeoPoint.DataBind();

			if (countryId > 0)
			{
				IEnumerable<IGeoItem> lRegions = new List<IGeoItem>(Region.GetAllRegions(countryId, null).Cast<IGeoItem>());
				if (!String.IsNullOrEmpty(startLetter))
				{
					lRegions = lRegions.Where(i => i.Name.StartsWith(startLetter));
				}

				CacheHelper.SetGeoItems(lRegions);

				rptGeoPoint.DataSource = lRegions;
				rptGeoPoint.DataBind();
			}
		}

		private void FillRegionsCombo(int countryId)
		{
			List<Region> lRegion = new List<Region>
                                           {
                                               new Region
                                                   {
                                                       Id = 0,
                                                       Name = NgoResource.resSelectRegionCombo
                                                   }
                                           };
			if (countryId > 0)
			{
				lRegion.AddRange(Region.GetAllRegions(countryId, true));
			}
			ddlRegion.DataSource = lRegion;
			ddlRegion.DataBind();
		}

		private void FillCities(int countryId, int? regionId, string startLetter)
		{
			rptGeoPoint.DataSource = null;
			rptGeoPoint.DataBind();

			if (countryId > 0)
			{
				IEnumerable<IGeoItem> lCities = new List<IGeoItem>(City.GetAllCities(countryId, regionId, null).Cast<IGeoItem>());
				if (!String.IsNullOrEmpty(startLetter))
				{
					lCities = lCities.Where(i => i.Name.StartsWith(startLetter));
				}

				CacheHelper.SetGeoItems(lCities);

				rptGeoPoint.DataSource = lCities;
				rptGeoPoint.DataBind();
			}
		}

		private void FillViewStateVariables()
		{
			string contentType = Request.QueryString["ct"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.GeographicPoint)), contentType) > -1)
			{
				CurrentGeographicPoint =
					(EnumHelper.GeographicPoint)Enum.Parse(typeof(EnumHelper.GeographicPoint), contentType);
			}

			string startLetter = Request.QueryString["l"];
			if (!String.IsNullOrEmpty(startLetter))
			{
				StartLetter = startLetter;
			}
		}

		private void FillPage()
		{
			ptTitle.Text = String.Format("{0} \"{1}\"", NgoResource.resListManager,
										 NgoResource.ResourceManager.GetString(
											 String.Format("resGeo{0}", CurrentGeographicPoint.ToString())));
			switch (CurrentGeographicPoint)
			{
				case EnumHelper.GeographicPoint.Countries:
					if (pnlCountries.Visible) pnlCountries.Visible = false;
					if (pnlRegions.Visible) pnlRegions.Visible = false;
					FillCountries(string.Empty);
					break;
				case EnumHelper.GeographicPoint.Regions:
					if (pnlRegions.Visible) pnlRegions.Visible = false;
					FillCountriesCombo();
					FillRegionsCombo(0);
					break;
				case EnumHelper.GeographicPoint.Cities:
					FillCountriesCombo();
					FillRegionsCombo(0);
					break;
			}

			FillLetterList();
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				FillViewStateVariables();
				FillPage();
			}
		}

		protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (!String.IsNullOrEmpty(ddlCountry.SelectedValue))
			{
				CountryId = Convert.ToInt32(ddlCountry.SelectedItem.Value);
				if (CurrentGeographicPoint == EnumHelper.GeographicPoint.Regions)
				{
					FillRegions(CountryId, string.Empty);
				}
				else if (CurrentGeographicPoint == EnumHelper.GeographicPoint.Cities)
				{
					FillRegionsCombo(CountryId);
					FillCities(CountryId, null, string.Empty);
				}
			}
		}

		protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
		{
			RegionId = Convert.ToInt32(ddlRegion.SelectedItem.Value);
			FillCities(CountryId, RegionId, string.Empty);
		}

		protected void rptAlphabetLinks_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "FilterByName")
			{
				string firstLetter = e.CommandArgument.ToString();

				if (e.CommandArgument.ToString() == "Список")
					firstLetter = string.Empty;

				switch (CurrentGeographicPoint)
				{
					case EnumHelper.GeographicPoint.Countries:
						FillCountries(firstLetter);
						break;
					case EnumHelper.GeographicPoint.Regions:
						FillRegions(CountryId, firstLetter);
						break;
					case EnumHelper.GeographicPoint.Cities:
						FillCities(CountryId, RegionId, firstLetter);
						break;
				}
			}
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			IEnumerable<IGeoItem> currentGeoItems = CacheHelper.GetGeoItems();

			if (currentGeoItems != null)
			{
				foreach (RepeaterItem ri in rptGeoPoint.Items)
				{
					CheckBox cbIsVisible = (CheckBox)ri.FindControl("cbIsVisible");
					if (cbIsVisible != null)
					{
						IGeoItem goItem = currentGeoItems.Where(i => i.Name == cbIsVisible.Text).FirstOrDefault();

						if (goItem != null && cbIsVisible.Checked != goItem.IsVisible)
						{
							goItem.IsVisible = cbIsVisible.Checked;
							goItem.Update();
						}
					}
				}
			}
		}
	}
}